<template>
  <a-modal :visible="visible" @ok="confirm" @cancel="$emit('cancel')" title="工作地点" :width="800" :confirmLoading="confirmLoading" destroyOnClose>
    <SelectCity :dataSource="dataSource" v-model="checkCity" defaultActiveKey="大陆" :spinning="spinning" :mode="mode"></SelectCity>
  </a-modal>
</template>

<script>
import SelectCity from '@/components/SelectCity/SelectCity'
export default {
  name: 'SelectCityModal',
  props: {
    visible: {
      type: Boolean,
      default: false,
      require: true
    },
    dataSource: {
      type: Array,
      default: () => [],
      require: true
    },
    spinning: {
      type: Boolean,
      default: false
    },
    confirmLoading: {
      type: Boolean,
      default: false
    },
    mode: {
      type: String,
      default: 'multiple' // single
    }
  },
  model: { prop: 'dataSource', event: 'change' },
  data () {
    return {
      checkCity: []
    }
  },
  components: {
    SelectCity
  },
  methods: {
    confirm () {
      // let obj = []
      // this.pushCity(this.checkCity, obj)
      const selectCity = JSON.parse(JSON.stringify(this.checkCity))
      selectCity.forEach(country => {
        for (let j = 0, province = country.children; j < province.length; j++) {
          if (province.checkAll === true) {
            province.children = []
          } else {
            for (let i = 0; i < province[j].children.length; i++) {
              if (!province[j].children[i].checked) {
                province[j].children.splice(i, 1)
                i--
              }
            }
          }
          if (!province[j].children.length && !province[j].checked && !province[j].checkAll) {
            province.splice(j, 1)
            j--
          }
        }
      })
      this.$emit('confirm', selectCity)
    },
    pushCity (city, newObj) {
      city.forEach(item => {
        if (item.checked) {
          if (!newObj.children) {
            newObj.children = [item]
          } else {
            newObj.children.push(item)
          }
        }
        if (item.children && item.children.length) {
          this.pushCity(item.children, newObj)
        }
      })
    }
  }
}
</script>

<style>

</style>
